package com.limh.readers.fragment

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import android.content.Intent
import android.content.SharedPreferences
import android.os.Handler
import android.os.Message
import android.support.annotation.Nullable
import android.support.v4.app.Fragment
import android.util.DisplayMetrics
import butterknife.ButterKnife
import com.limh.readers.bean.User
import com.limh.readers.fragment.BaseFragment.Companion.fragmentSet
import com.limh.readers.utils.GsonUtils
import com.limh.readers.utils.SharePreferUtils


/**
 * Created by limh on 2017/7/3.
 * Fragment基类
 */
abstract class BaseFragment : Fragment() {
    var width: Int? = 0

    companion object {
        var fragmentSet: Set<BaseFragment> = HashSet()
    }

    lateinit var userPreference: SharedPreferences

    override fun onCreateView(inflater: LayoutInflater?, @Nullable container: ViewGroup?, @Nullable savedInstanceState: Bundle?): View? {
        val view: View = findViews(inflater, container)
        ButterKnife.bind(this, view)
        userPreference = activity.getSharedPreferences("USER", Context.MODE_PRIVATE)
        val wm = activity.windowManager
        val dm = DisplayMetrics()
        wm.defaultDisplay.getMetrics(dm)
        width = dm.widthPixels

        initViews()
        initDatas()
        return view
    }

    /**
     * 设置fragment的布局资源,找到需要的控件
     */
    abstract fun findViews(inflater: LayoutInflater?, container: ViewGroup?): View

    abstract fun initViews()

    abstract fun initDatas()

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        fragmentSet.plus(this)
    }

    fun showToastLong(msg: String) {
        Toast.makeText(activity, msg, Toast.LENGTH_LONG).show()
    }

    fun showToastShort(msg: String) {
        Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show()
    }

    fun openActivity(calss: Class<*>) {
        val intent = Intent()
        intent.setClass(activity, calss)
        startActivity(intent)
    }

    fun sendMsg(msg: String, what: Int, handler: Handler) {
        val bundle = Bundle()
        bundle.putString("msg", msg)
        val message = Message()
        message.what = what
        message.data = bundle
        handler.sendMessage(message)
    }
}